import Foundation
import ProgressHUD

class ProgressHUDQueue {
  private var queue: [(type: String, message: String, duration: TimeInterval)] = []
  private var isShowing = false

  static let shared = ProgressHUDQueue()

  private init() {}

  // 添加一个新的提示到队列
  func addToQueue(type: String, message: String, duration: TimeInterval = 2) {
    queue.append((type, message, duration))
    if !isShowing {
      showNext()
    }
  }

  func dismiss() {
    isShowing = false
  }

  // 显示队列中的下一个提示
  private func showNext() {
    //        guard queue.count > 0 else {
    //            isShowing = false
    //            return
    //        }
    let item = queue.removeFirst()
    isShowing = true

    // 根据提示类型执行不同操作
    switch item.type {
    case "succeed":
      ProgressHUD.succeed(item.message)
      DispatchQueue.main.asyncAfter(deadline: .now() + item.duration) {
        self.showNext()
      }
    case "animate":
      ProgressHUD.animate(item.message, interaction: false)
      DispatchQueue.main.asyncAfter(deadline: .now() + item.duration) {
        self.showNext()
      }
    case "failed":
      ProgressHUD.failed(item.message, interaction: false)
      DispatchQueue.main.asyncAfter(deadline: .now() + item.duration) {
        self.showNext()
      }
    default:
      break
    }
  }
}

extension ProgressHUD {
  static func queueSucceed(_ message: String, duration: TimeInterval = 2) {
    ProgressHUDQueue.shared.addToQueue(type: "succeed", message: message, duration: duration)
  }

  static func queueAnimate(_ message: String, duration: TimeInterval = 2) {
    ProgressHUDQueue.shared.addToQueue(type: "animate", message: message, duration: duration)
  }

  static func queueFailed(_ message: String, duration: TimeInterval = 2) {
    ProgressHUDQueue.shared.addToQueue(type: "failed", message: message, duration: duration)
  }
}
